package cn.sky.demo.hander.interceptor;


import cn.sky.demo.domain.entity.User;
import cn.sky.demo.enums.AppHttpCodeEnum;
import cn.sky.demo.exception.SystemException;
import cn.sky.demo.service.UserService;
import cn.sky.demo.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("token");

        log.info("===============request start===============");
        log.info("request uri:{}", request.getRequestURI());
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("===============request end===============");

        if (StringUtils.isEmpty(token)) {
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
        User user = userService.checkToken(token);
        if (user == null) {
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
        UserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
